<?php
declare (strict_types = 1);

namespace app\model;

use app\common\service\redis\PoolRedis;
use think\facade\Request;
use think\Model;

/**
 * @mixin \think\Model
 */
class AdminSchool extends Model
{
    const SCHOOL_CACHE_KEY = 'school:';

    //
    public function unlock() {
        return $this->hasMany(AdminSchoolRkeRecord::class, 'school_id');
    }

    // 新增后
    public static function onAfterInsert($AdminSchool)
    {
        $school = $AdminSchool->toArray();
        $user = AdminUser::create([
            'username' => $school['account'],
            'nickname' => $school['name'],
            'password' => $school['password'],
            'create_ip' => sprintf("%u", ip2long(Request::ip())),
            'school_id' => $school['id'],
            'status' => 1
        ]);
        AdminAuthGroupAccess::create([
            'uid'      => $user->id,
            'group_id' => '1'
        ]);
    }

    public static function onAfterWrite($model)
    {
        $key = self::SCHOOL_CACHE_KEY.$model->getAttr('id');
        $redis = PoolRedis::instance();
        $redis->delete($key);
    }

    // 更新后
    public static function onAfterUpdate($AdminSchool)
    {
        $school = $AdminSchool->toArray();
        if ($AdminSchool->getAttr('is_delete') == 1) {
            $user = AdminUser::where([
                'school_id' => $AdminSchool->getAttr('id'),
                'username' => $AdminSchool->getAttr('account')
            ])->find();
            $group = AdminAuthGroupAccess::where('uid', $user->id)->find();
            $group->delete();
            $user->delete();
            AdminDormitory::update(['is_delete' => 1], ['school_id' => $AdminSchool->getAttr('id'), 'is_delete' => 0]);

            self::delKeyHandler($AdminSchool->getAttr('id'));
        }
    }

    // 删除后
    public static function onAfterDelete($AdminSchool)
    {
        $user = AdminUser::where([
            'school_id' => $AdminSchool->getAttr('id'),
            'username' => $AdminSchool->getAttr('account')
        ])->find();
        $group = AdminAuthGroupAccess::where('uid', $user->id)->find();
        $group->delete();
        $user->delete();
        AdminDormitory::update(['is_delete' => 1], ['school_id' => $AdminSchool->getAttr('id'), 'is_delete' => 0]);

        self::delKeyHandler($AdminSchool->getAttr('id'));
    }

    public static function delKeyHandler($school_id, $origin = [])
    {
        $redis = PoolRedis::instance();
        $redis->multi();
        $redis->del(AdminStaff::SCHOOL_SEX_GROUP.$school_id);
        $redis->del(AdminDormitory::DORMITORY_COUNT_CACHE_KEY."school_".$school_id);
        $redis->exec();
    }
}
